package com.czy.owner.ui.login;


import android.Manifest;
import android.content.Intent;
import android.os.Build;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.czy.owner.R;
import com.czy.owner.global.Constants;
import com.czy.owner.net.utils.JsonUtil;
import com.czy.owner.permission.Acp;
import com.czy.owner.permission.AcpListener;
import com.czy.owner.permission.AcpOptions;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.utils.ActivityHelper;
import com.czy.owner.utils.GetDeviceId;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.widget.MyEditText;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * Created by wangyang on 2016/5/23.
 * 忘记密码
 */

public class ForgetPasswordActivity extends BaseActivity {
    @BindView(R.id.et_wangji_psw_input_phone)
    MyEditText etForgetPasswordInputPhone;
    @BindView(R.id.et_input_yanzhangma)
    EditText etInputCode;
    @BindView(R.id.tv_get_yanzhengma)
    TextView tvGetCode;
    @BindView(R.id.et_reset_psw)
    MyEditText etResetPasssword;
    @BindView(R.id.et_reset_psw_again)
    MyEditText etResetPasswordAgain;


    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_forget_password_msg_code;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        getToolbarTitle().setText(R.string.forget_psd);
    }

    @Override
    protected void updateViews() {

    }

    @OnClick(R.id.tv_get_yanzhengma)
    public void tvGetGodeOnClick(View view) {
        String phone = etForgetPasswordInputPhone.getText().toString().trim();

        if (!PhoneUtils.isNetworkConnected(ForgetPasswordActivity.this)) {
            return;
        }

        if (TextUtils.isEmpty(phone)) {
            PhoneUtils.ShowToastMessage(ForgetPasswordActivity.this, getString(R.string.phone_error_null));
            etForgetPasswordInputPhone.requestFocus();
            return;
        }

        if (!PhoneUtils.isMobileNO(phone)) {
            PhoneUtils.ShowToastMessage(ForgetPasswordActivity.this, getString(R.string.phone_error));
            etForgetPasswordInputPhone.requestFocus();
            return;
        }

        RequestParams params = new RequestParams(Constants.APP_API_BASE + Constants.FORGET_PASSWORD_GETCODE_API);
        params.addBodyParameter("phone", phone);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                String exp = JsonUtil.getJsonValuesString(result, "exp");
                String flag = JsonUtil.getJsonValuesString(result, "flag");
                if (flag.equals("true")) {
                    timer.start();
                } else {
                    PhoneUtils.ShowToastMessage(ForgetPasswordActivity.this, exp);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });


    }


    @OnClick(R.id.btn_next)
    public void btnNextOnClick(View view) {
        String code = etInputCode.getText().toString().trim();
        String phone = etForgetPasswordInputPhone.getText().toString().trim();
        String resetPassword = etResetPasssword.getText().toString().trim();
        String resetPasswordAgain = etResetPasswordAgain.getText().toString().trim();

        if (!PhoneUtils.isNetworkConnected(ForgetPasswordActivity.this)) {
            return;
        }

        if (TextUtils.isEmpty(phone)) {
            PhoneUtils.ShowToastMessage(ForgetPasswordActivity.this, getString(R.string.phone_error_null));
            etForgetPasswordInputPhone.requestFocus();
            return;
        }
        if (!PhoneUtils.isMobileNO(phone)) {
            PhoneUtils.ShowToastMessage(ForgetPasswordActivity.this, getString(R.string.phone_error));
            etForgetPasswordInputPhone.requestFocus();
            return;
        }

        if (TextUtils.isEmpty(code)) {
            PhoneUtils.ShowToastMessage(ForgetPasswordActivity.this, getString(R.string.code_error_null));
            etInputCode.requestFocus();
            return;
        }
        if (TextUtils.isEmpty(resetPassword)) {
            PhoneUtils.ShowToastMessage(ForgetPasswordActivity.this, getString(R.string.new_password_no));
            etResetPasssword.requestFocus();
            return;

        }


        if (!resetPassword.equals(resetPasswordAgain)) {
            PhoneUtils.ShowToastMessage(ForgetPasswordActivity.this, getString(R.string.twice_new_password_disagree));
            etResetPasswordAgain.requestFocus();
            return;
        }


        if (resetPassword.length() < 6 && resetPassword.length() > 20) {
            PhoneUtils.ShowToastMessage(ForgetPasswordActivity.this, getString(R.string.input_psd_length));
            return;
        }

        if ((Build.VERSION.SDK_INT >= 23)) {
            phoneStatePermissions(phone, resetPassword,code);
        } else {
            GetDeviceId getDeviceId = new GetDeviceId(ForgetPasswordActivity.this);
            pid = getDeviceId.getCombinedId();
            MyLog.e("yang", "忘记密码pid==" + pid);
            UserForgetPswApi(phone, resetPassword, code);
        }


    }




    public String pid = "";
    public void phoneStatePermissions(final String phone, final String resetPassword,final String code) {
        Acp.getInstance(ForgetPasswordActivity.this).request(new AcpOptions.Builder().setPermissions(Manifest.permission.READ_PHONE_STATE).build(),
                new AcpListener() {
                    @Override
                    public void onGranted() {
                        GetDeviceId getDeviceId = new GetDeviceId(ForgetPasswordActivity.this);
                        pid = getDeviceId.getCombinedId();
                        MyLog.e("yang", "忘记密码pid==" + pid);
                        UserForgetPswApi(phone, resetPassword, code);
                    }

                    @Override
                    public void onDenied(List<String> permissions) {
                        PhoneUtils.ShowToastMessage(ForgetPasswordActivity.this, "获取手机权限拒绝");

                    }
                });
    }



    private void UserForgetPswApi(final String phone, final String resetPassword, final String code) {
        mLoadView.ShowLoadView();
        RequestParams params = new RequestParams(Constants.APP_API_BASE + Constants.RESET_PASSWORD_API);
        params.addBodyParameter("phone", phone);
        params.addBodyParameter("newPassword", resetPassword);
        params.addBodyParameter("smsCode", code);
        params.addBodyParameter("pid", pid);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                String exp = JsonUtil.getJsonValuesString(result, "exp");
                String flag = JsonUtil.getJsonValuesString(result, "flag");
                if (flag.equals("true")) {
                    ActivityHelper.getInstance().finishAllActivity();
                    startActivity(new Intent(ForgetPasswordActivity.this, LoginActivity.class));
                    PhoneUtils.ShowToastMessage(ForgetPasswordActivity.this, "密码修改成功");
                } else {
                    PhoneUtils.ShowToastMessage(ForgetPasswordActivity.this, exp);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                mLoadView.CancleLoadView();
            }
        });
    }


    //   倒计时响应事件  timer.start();
    private CountDownTimer timer = new CountDownTimer(60000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            tvGetCode.setClickable(false);// 设置不能点击
            tvGetCode.setText(millisUntilFinished / 1000 + getString(R.string.send_again));// 设置倒计时时间
            tvGetCode.setTextColor(getResources().getColor(R.color.appTipColor)); // 设置为灰色，这时是不能点击的
        }

        @Override
        public void onFinish() {
            tvGetCode.setText(getResources().getString(R.string.get_yanzhengma));
            tvGetCode.setClickable(true);// 重新获得点击
            tvGetCode.setTextColor(getResources().getColor(R.color.appThemeColor));

        }
    };


}
